package servlet;



import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ValidateCodeServlet extends HttpServlet {
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// /img/ValidateCodeServlet
		response.setContentType("image/gif");
		OutputStream out = response.getOutputStream();
		HttpSession session = request.getSession();
		
		BufferedImage img = new BufferedImage(200, // 宽度
				40, // 高度
				BufferedImage.TYPE_INT_RGB);// 颜色类型

		String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String validateCode="";
		Graphics g = img.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, 200, 40);
		Random r = new Random();
		for (int i = 0; i < 4; i++) {
			char c = s.charAt(r.nextInt(s.length()));
			validateCode+=c;
			g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
			g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC,
					r.nextInt(17) + 20));
			g.drawString(String.valueOf(c), 50 * i + 10, 38);
		}

		session.setAttribute("validateCode", validateCode);
		for (int i = 0; i < 3; i++) {
			int x1 = r.nextInt(200);
			int y1 = r.nextInt(40);
			int x2 = r.nextInt(200);
			int y2 = r.nextInt(40);
			g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
			g.drawLine(x1, y1, x2, y2);
		}
		ImageIO.write(img, "gif", out);

	}
}
